const intervalDuration = 1000; // 1 second
let beforeElement = undefined;
const checkElement = () => {
    const targetElement = document.querySelector('.wp-info-wrapper');
    if (targetElement && targetElement !== beforeElement) {
        // 创建按钮元素
        const button = document.createElement('button');
        button.textContent = '同步WoLai';
        button.style.backgroundColor = '#67C23A'; // 恢复初始颜色为红色
        button.style.color = '#333333';
        button.style.border = 'none';
        button.style.padding = '5px 10px';
        button.style.cursor = 'pointer';
        button.style.margin = '0px 6px 8px 0px';
        updateSyncCount(button); // 更新同步次数
        // 添加点击事件监听器
        button.addEventListener('click', () => {
            button.style.backgroundColor = 'gray'; // 改变按钮颜色为灰色
            button.disabled = true; // 禁用按钮以防止重复点击
            button.textContent = '同步中'

            let syncTextIndex = 0;
            const syncTexts = ['同步中.', '同步中..', '同步中...'];
            const intervalId = setInterval(() => {
                button.textContent = syncTexts[syncTextIndex];
                syncTextIndex = (syncTextIndex + 1) % syncTexts.length;
            }, 200); // 每500毫秒切换一次文本

            syncToWolai(button).then(() => {
                clearInterval(intervalId); // 停止文字变化
                updateSyncCount(button); // 更新同步次数
                button.disabled = false; // 启用按钮
            }).catch(() => {
                clearInterval(intervalId); // 停止文字变化
                button.style.backgroundColor = '#67C23A'; // 恢复按钮颜色为红色
                button.disabled = false; // 启用按钮
            });
        });

        // 将按钮插入到 targetElement 的首位
        targetElement.insertBefore(button, targetElement.firstChild);
        beforeElement = targetElement
    }
};

setInterval(checkElement, intervalDuration);

// 获取 token
const getToken = async () => {
    const {appId, appSecret} = await chrome.storage.sync.get(['appId', 'appSecret']);
    const response = await fetch('https://openapi.wolai.com/v1/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            appId: appId,
            appSecret: appSecret
        })
    });
    const data = await response.json();
    return data.data.app_token;
};

// 新增待办事项
const createTodo = async (token) => {
    const href = window.location.href
    const {groupBy, groupName, dataId} = await chrome.storage.sync.get(['groupBy', 'groupName', 'dataId']);
    const op = "☕️OP-" + href.match(/.+\/work_packages\/(\d+)\/(activity|relations)/)[1]
    let block = {
        "标题": document.querySelector("div.work-packages--details--subject").textContent,
        "OP号": op,
        "OP地址": href
    }
    block[groupBy] = groupName
    const response = await fetch(`https://openapi.wolai.com/v1/databases/${dataId}/rows`, {
        method: 'POST',
        headers: {
            'Authorization': token,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            rows: [block]
        })
    });
    const data = await response.json();
    let dataUrl = data.data[0]
    return dataUrl.replace('https://www.wolai.com/', '')
};

// 给待办事项添加详情信息
const addDetailsToTodo = async (token, todoId, op) => {
    let first = [
        {
            "type": "heading",
            "level": 1,
            "content": [
                {
                    "title": "OP内容 - ",
                    "type": "text",
                    "front_color": "#E6A23C"
                },
                {
                    "title": op,
                    "front_color": "blue",
                    "type": "text",
                    "link": window.location.href
                }
            ],
            "text_alignment": "left"
        },
        {
            "type": "quote",
            "content": [
                {
                    "title": document.querySelector("div.work-packages--details--description").textContent,
                    "type": "text"
                }
            ]
        },
        {
            "type": "divider"
        },
        {
            "type": "heading",
            "level": 1,
            "content": {
                "title": "开发记录",
                "front_color": "#E6A23C"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "toggle": true,
            "level": 2,
            "content": {
                "title": "开发草稿",
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "toggle": true,
            "level": 2,
            "content": [
                {
                    "type": "text",
                    "title": "测试关注",
                }
            ],
            "text_alignment": "left"
        },
        {
            "type": "divider"
        },
        {
            "type": "heading",
            "level": 1,
            "content": {
                "title": "发布内容",
                "front_color": "#E6A23C"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "toggle": true,
            "level": 2,
            "content": {
                "title": "Pull Request",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "toggle": true,
            "level": 2,
            "content": {
                "title": "Apollo + CMS + SQL配置",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "toggle": true,
            "level": 2,
            "content": {
                "title": "发布TAG",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "toggle": true,
            "level": 2,
            "content": {
                "title": "日志监控",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        }
    ]

    // 先创建父类目
    let firstResponse = await fetch('https://openapi.wolai.com/v1/blocks', {
        method: 'POST',
        headers: {
            'Authorization': token,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            parent_id: todoId,
            blocks: first
        })
    });
    // 再根据父类目插入子类目
    const firstResponseData = await firstResponse.json();

    // 测试关注插入
    let dataIdUrl = firstResponseData.data[5]
    let dataIdIndex = dataIdUrl.indexOf("#")
    let parent_id = dataIdUrl.substring(dataIdIndex + 1)
    let second = [
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "1. 相关服务",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "2. 相关接口",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "3. 相关Redis Key",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "4. 相关SQL语句",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        }
    ]
    await fetch('https://openapi.wolai.com/v1/blocks', {
        method: 'POST',
        headers: {
            'Authorization': token,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            parent_id: parent_id,
            blocks: second
        })
    });

    // 配置插入
    dataIdUrl = firstResponseData.data[9]
    dataIdIndex = dataIdUrl.indexOf("#")
    parent_id = dataIdUrl.substring(dataIdIndex + 1)
    second = [
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "1. Apollo",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "2. CMS",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        },
        {
            "type": "heading",
            "level": 4,
            "content": {
                "title": "3. SQL",
                "front_color": "#67C23A"
            },
            "text_alignment": "left"
        }
    ]
    await fetch('https://openapi.wolai.com/v1/blocks', {
        method: 'POST',
        headers: {
            'Authorization': token,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            parent_id: parent_id,
            blocks: second
        })
    });
};

// 同步到 Wolai 平台
const syncToWolai = async (button) => {
    try {
        const token = await getToken();
        const todoId = await createTodo(token);
        const href = window.location.href;
        const opNumber = href.match(/.+\/work_packages\/(\d+)\/(activity|relations)/)[1]
        await addDetailsToTodo(token, todoId, opNumber);
        // 更新同步次数
        const op = "OP-" + opNumber;
        const syncCount = localStorage.getItem(op) ? parseInt(localStorage.getItem(op)) : 0;
        localStorage.setItem(op, syncCount + 1);
        updateSyncCount(button); // 更新同步次数显示
    } catch (error) {
        console.log(error)
        alert('同步失败:' + JSON.stringify(error));
    }
};

// 更新同步次数显示
const updateSyncCount = (button) => {
    const href = window.location.href;
    const op = "OP-" + href.match(/.+\/work_packages\/(\d+)\/(activity|relations)/)[1];
    const syncCount = localStorage.getItem(op) ? parseInt(localStorage.getItem(op)) : 0;
    if (syncCount > 0) {
        button.textContent = `同步WoLai(${syncCount})`;
        button.style.backgroundColor = '#E6A23C';
    } else {
        button.style.backgroundColor = '#67C23A'; // 恢复按钮颜色为红色
    }
};